import java.util.Locale;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.HttpEntityWrapper;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClients;
import org.apache.http.impl.nio.conn.PoolingNHttpClientConnectionManager;
import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor;
import org.apache.http.impl.nio.reactor.IOReactorConfig;
import org.apache.http.nio.reactor.ConnectingIOReactor;
import org.apache.http.nio.reactor.IOReactorException;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.util.EntityUtils;

public class TestRequest {
	public static String getServiceUrl(String targetUrl,String idmToken)throws Exception{
//        String idmUrl = "https://login.tcl.com/siam/login?service=http://wcs.tcl.com/wcs/";
        System.setProperty ("jsse.enableSNIExtension", "false");
        String cookie = "SIAMTGT="+idmToken+";Domain=127.0.0.1;Path=/";
//        CloseableHttpAsyncClient httpClient =  HttpAsyncClients.createDefault();
//        httpClient.start();
        HttpGet method = new HttpGet(targetUrl);
        method.setHeader("Content-Type","text/html");
        method.setHeader("Accept","text/html, application/xhtml+xml, */*");
        method.setHeader("Accept-Language","zh-CN");
        method.setHeader("User-Agent","Mozilla/5.0 (Linux; U; Android 6.0.3; ko-kr; LG-L160L Build/IML74K) AppleWebkit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30 ");
        method.setHeader("UA-CPU","AMD64");
        method.setHeader("Accept-Encoding","gzip, deflate");
        method.setHeader("Connection","Keep-Alive");
        method.setHeader("Cookie",cookie);
        String ticket = null;
        HttpResponse resp = client().execute(method,null).get();
            org.apache.http.HttpEntity entity = resp.getEntity();
            String oaResp = null;
            if (entity != null) {
                //按指定编码转换结果实体为String类型
                oaResp = EntityUtils.toString(entity, "UTF-8");
            }
            String respTicket = null;
            if (null != resp.getFirstHeader("location")){
                respTicket = resp.getFirstHeader("location").getValue();
            }
                return respTicket;
	}
	
	public static CloseableHttpAsyncClient client() {
		RequestConfig requestConfig = 
				RequestConfig.custom()
				.setConnectTimeout(50000)
				.setSocketTimeout(50000)
				.setConnectionRequestTimeout(10)// 设置为10ms
				.setRedirectsEnabled(false)
				.build();
		boolean l = requestConfig.isRedirectsEnabled();
		// 配置io线程
		IOReactorConfig ioReactorConfig = IOReactorConfig.custom()
				.setIoThreadCount(Runtime.getRuntime().availableProcessors()).setSoKeepAlive(true).build();
		// 设置连接池大小
		ConnectingIOReactor ioReactor = null;
		try {
			ioReactor = new DefaultConnectingIOReactor(ioReactorConfig);
		} catch (IOReactorException e) {
			e.printStackTrace();
		}
		PoolingNHttpClientConnectionManager connManager = new PoolingNHttpClientConnectionManager(ioReactor);
		connManager.setMaxTotal(1);// 最大连接数设置1
		connManager.setDefaultMaxPerRoute(1);// per route最大连接数设置1
		CloseableHttpAsyncClient client = HttpAsyncClients.custom().setConnectionManager(connManager)
				.setDefaultRequestConfig(requestConfig).build();
		client.start();
		return client;
	}
	
	public static void main(String[] args) throws Exception {
//		httpRequest("http://127.0.0.1:28080/siam/login?service=http://127.0.0.1:8083/cas/cas2", "TGT-7-wUIf2EQHlYDZgncXg9HgCjvkVcDpJgMkhDnd4g7oSOBjINbrec-SIAM");
		getServiceUrl("http://127.0.0.1:28080/siam/login?service=http://127.0.0.1:8083/cas/cas", "TGT-7-wUIf2EQHlYDZgncXg9HgCjvkVcDpJgMkhDnd4g7oSOBjINbrec-SIAM");
	}
	
	public static String httpRequest(String url,String idmToken) {
		HttpGet httpGet = null;
		CloseableHttpResponse httpResponse = null;
		CloseableHttpClient httpClient = null;
		try {
			int CONNECTION_TIMEOUT = 1000 * 1000;
			httpClient = HttpClients.createDefault();
			RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(CONNECTION_TIMEOUT)
					.setConnectTimeout(CONNECTION_TIMEOUT).setSocketTimeout(CONNECTION_TIMEOUT).build();
			httpGet = new HttpGet(url);
			httpGet.setConfig(requestConfig);
			httpGet.addHeader("Content-Type", "application/json");
//			httpGet.addHeader("Authorization", "Basic " + token);
			
			
			String cookie = "SIAMTGT="+idmToken+";Domain=127.0.0.1;Path=/";
			
			httpGet.setHeader("Content-Type","text/html");
			httpGet.setHeader("Accept","text/html, application/xhtml+xml, */*");
			httpGet.setHeader("Accept-Language","zh-CN");
			httpGet.setHeader("User-Agent","Mozilla/5.0 (Linux; U; Android 6.0.3; ko-kr; LG-L160L Build/IML74K) AppleWebkit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30 ");
			httpGet.setHeader("UA-CPU","AMD64");
			httpGet.setHeader("Accept-Encoding","gzip, deflate");
			httpGet.setHeader("Connection","Keep-Alive");
			httpGet.setHeader("Cookie",cookie);
			
			long time1 = System.currentTimeMillis();
			httpResponse = httpClient.execute(httpGet, new BasicHttpContext());
			HttpEntity entity = httpResponse.getEntity();
			if (entity != null) {
				Locale locale = httpResponse.getLocale();
				Header[] headers = httpResponse.getAllHeaders();
				Header header = httpResponse.getFirstHeader("Location");
				String resultStr = EntityUtils.toString(entity, "UTF-8");
				HttpEntityWrapper responseEntityWrapper = (HttpEntityWrapper)entity;
				responseEntityWrapper.getContentEncoding();
				System.out.println(resultStr);
				return resultStr;
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (httpResponse != null) {
				try {
					httpResponse.close();
				} catch (Exception e) {
				}
			}
			if (httpGet != null) {
				try {
					httpGet.releaseConnection();
				} catch (Exception e) {
				}
			}
			if (httpClient != null) {
				try {
					httpClient.close();
				} catch (Exception e) {
				}
			}
		}
		return null;
	}
            
}
